package config

import (
	"github.com/spf13/viper"
	"log"
	"os"
	"path/filepath"
	"token-for-token/global"
)

type Config struct {
	vp *viper.Viper
}

func NewConfig() (*Config, error) {
	// 获取可执行文件的绝对路径
	exec, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	// 基于可执行文件的路径构建配置文件的绝对路径
	configPath := filepath.Join(exec, "config", "config.yaml")
	viper.SetConfigFile(configPath)
	vp := viper.New()
	vp.SetConfigName("config")
	vp.AddConfigPath("config")
	vp.SetConfigType("yaml")
	err = vp.ReadInConfig()
	if err != nil {
		return nil, err
	}
	return &Config{vp}, nil
}

func (config *Config) ReadSection(k string, v interface{}) error {
	err := config.vp.UnmarshalKey(k, v)
	if err != nil {
		return err
	}
	return nil
}

func SetupConfig() {
	conf, err := NewConfig()
	if err != nil {
		log.Panic("NewConfig error : ", err)
	}
	err = conf.ReadSection("Database", &global.DbConfig)
	if err != nil {
		log.Panic("ReadSection - Database error : ", err)
	}
}
func SetupDBEngine() {
	var err error
	global.DBEngine, err = NewDBEngine(global.DbConfig)
	if err != nil {
		log.Panic("NewDBEngine error : ", err)
	}
}
